// vip/vip.js
const api = require("../request/api")
const request = require("../request/request")
const util = require("../utils/util")
const App = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

let cards = ['普通', '银卡', '金卡', '钻石卡']
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
        barHeight: App.globalData.paddingTop,

        avatarUrl: defaultAvatarUrl,
        nickName: '游客',
        islogin: false,
        isVip: false,
        uid: '',
        myinfo: {},

        more_list: [],
        if_get_avatart: false,
        styledata: {
            "bg_color": "#fff",
            "color": "#000",
            "leftflag": true,
            "homeflag": true,
            "name": "会员中心"
        },

        endTime: '',
        VipGrade: 0,
        card: cards[0]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function () {
        let userInfo = App.globalData.userInfo
        if (!userInfo.uid) {
            let flag = await App.confirmLogin('您未登录')
            if (!flag) {
                wx.navigateBack()
                return
            }
        }
        // this.init_data()
        this.get_more_list()
    },

    init_data() {
        let endTime = ''
        if (App.globalData.VipGrade > 0) {
            endTime = App.globalData.fulluserInfo.end_time
            let arr = endTime.split(' ')
            endTime = arr[0].replace(/-/g, '/')
        }
        this.setData({
            islogin: App.globalData.islogin,
            uid: App.globalData.uid,
            isVip: App.globalData.isVip,
            VipGrade: App.globalData.VipGrade,
            avatarUrl: App.globalData.fulluserInfo?.avatar || defaultAvatarUrl,
            nickName: App.globalData.fulluserInfo?.name || '游客',
            endTime,
            card: cards[App.globalData.VipGrade]
        })
    },

    setDefaultAvatar() {
        this.setData({
            avatarUrl: defaultAvatarUrl
        })
    },

    go_detail_from_component(e) {
        let id = e.detail.currentTarget.dataset.id
        if (!id) {
            id = 10
        }
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },
    check_register() {
        console.log('check register')
        if (wx.getStorageSync('is_login') == false) {
            //this.get_user_profile()
            wx.login({
                success: res => {
                    let params = {
                        code: res.code
                    }
                    util.showLoading('正在加载')
                    //let userInfo = wx.getStorageSync('userInfo')
                    let userInfo = { avatarUrl: '', nickName: '' }
                    if (true) {
                        request.post(api.login, params).then(res => {
                            App.globalData.userInfo = res
                            userInfo.avatarUrl = res.avatarUrl
                            userInfo.nickName = res.nickName
                            wx.setStorageSync('uid', res.uid)
                            wx.setStorageSync('openId', res.openId)
                            wx.setStorageSync('userInfo', userInfo)
                            wx.setStorageSync('is_login', true)
                            //wx.setStorage('uid',res)
                            console.log(res)
                            util.saveAppValue(App.globalData.uid, res.uid);
                            util.hideLoading()
                        })
                    } else {
                        //console.log( wx.getStorageSync('userInfo') )
                        util.hideLoading()
                    }
                },
                fail: res => {
                    console.log(res);
                }
            })
        }
    },
    get_user_profile() {
        wx.getUserProfile({
            desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: res => {
                wx.setStorageSync('userInfo', res.userInfo)
                wx.setStorageSync('is_login', true)
                let userInfo2 = wx.getStorageSync('userInfo')
                //console.log(userInfo2)
                // App.globalData.userInfo = res.userInfo
                // App.globalData.if_register = true
                this.init_data(this.data.options)
                // let pages = getCurrentPages()
                // let prev_page = pages[pages.length - 2]
                // prev_page.onLoad()
                // util.goBack()
            },
            fail: res => {
                console.log(res);
            }
        })
    },
    set_avatar(avatar) {
        let params = { "uid": this.data.uid, "img": avatar }
        request.post(api.set_avatar, params).then(res => {
            console.log(res)
        })
    },
    get_more_list() {
        let params = {
            // uid: this.data.uid
            // brand_id: 2
        }
        util.showLoading('加载中')
        request.post(api.goods_more, params).then(res => {
            util.hideLoading()
            for (var i = 0; i < res.length; i++) {
                let mx = parseInt(Math.random() * 10) / 10
                let youhui = res[i].sell_price * (mx * 0.04 + 0.08)
                res[i].youhui = youhui.toFixed(2)
            }
            this.setData({
                more_list: res
            })
        })
    },

    // 商品列表组件点击加入购物车
    async cart_add(e) {
        if (!this.data.uid) {
            util.showToast('请登录后再添加购物车哦')
            return
        }
        let id = e.detail.currentTarget.dataset.id
        let goodDetail = await request.post(api.goods_details, { id })
        if (goodDetail.store_nums <= 0) {
            wx.showToast({
                title: '该商品暂无库存，请挑选别的心仪商品吧',
                icon: 'none',
                duration: 2000
            });
            return
        }

        // 筛选最低价格规格id，默认选最低规格
        let temArr = []
        goodDetail.products_array.forEach(item => {
            temArr.push(item.sell_price)
        });
        let lowestProPrice = Math.min(...temArr)
        let lowestIndex = temArr.indexOf(lowestProPrice)
        let skuid = goodDetail.products_array[lowestIndex].id
        // console.log('skuid', skuid);

        let params = {
            goods_id: id,
            uid: this.data.uid,
            goods_sku_id: skuid
        }
        let res = await request.post(api.cart_add, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums

            // this.handleChangeCart()
        }
        util.showToast("已加入购物车")
    },

    go_buy_vip(e) {
        let id = e.currentTarget.dataset.chosenid

        // if (!this.data.if_register) {
        //   util.showToast("请先登录")
        //   return
        // }
        // let url = `/vip/buy_vip?chosenid=${id}`

        let url = `/vip/buy_vip`
        wx.navigateTo({
            url,
        })
    },
    changeAvatar() {
        let url = '/pages/myinfo/avatar'
        wx.navigateTo({
            url,
        })
    },
    onChooseAvatar(e) {
        const { avatarUrl } = e.detail
        this.setData({
            avatarUrl,
            if_get_avatar: true
        })
        this.set_avatar(avatarUrl)
        let userInfo = wx.getStorageSync('userInfo')
        if (userInfo) {
            userInfo.avatarUrl = avatarUrl
            wx.setStorageSync('userInfo', userInfo)
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 检测是否有头像昵称修改
        // let isVip = App.globalData.isVip
        // let avatarUrl = App.globalData?.fulluserInfo?.avatar
        // let nickName = App.globalData?.userInfo?.nickName
        // if (this.data.isVip != isVip || this.data.avatarUrl != avatarUrl || this.data.nickName != nickName) {
        this.init_data()
        // }

        // 检测是否有个人信息
        // if (!this.data.myinfo.name && this.data.uid) {
        //     this.get_myinfo()
        // }
    },

    get_myinfo() {
        let params = {
            uid: this.data.uid
        }
        request.post(api.myinfo, params).then(res => {
            this.setData({
                myinfo: res
            })
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})